<?php
require_once 'DB.php';

define('GW_GAME_DATA','./game_data');
define('DSN_GAME','mysql://root:urpig@127.0.0.1/gw');
class gError {
}

class Game {
    var $mId=null;
    var $mAttrs=array();
    var $_loaded=false;
    function Game($id) {
        $this->mDB=new DB(DSN_GAME);
        if (!preg_match('/^[0-9]+$/',$id)) {
        }
        $this->mId = $id;
    }
    function get($attr) {
        if (!$this->_loaded) {
            $this->_load();
        }
        isset($this->mAttrs[$attr])?$this->mAttrs[$attr]:false;
    }
    function save() {
        foreach (GWHook::get('game_save') as $func) {
            $func($this->mAttrs);
        }
        $sql = 'UPDATE game SET updated_time='.time().' WHERE gid='.$this->mId;
        $this->mDB->initSql($sql);
        $this->mDB->query();
        return file_put_contents(GW_GAME_DATA.'/'.$this->mId.'.php','<?php $_game_attrs='.var_export($this->mAttrs,true).';');
    }
    function getAll() {
        if (!$this->_loaded) {
            $this->_load();
        }
        return $this->mAttrs;
    }
    function _load() {
        include(GW_GAME_DATA.'/'.$this->mId);
        $this->mAttrs = $_game_attrs;
    }
}

class GameList {
    function getByTime() {
    }
    function getByPlatform($pid) {
    }
    function getByTeam($tid) {
    }
}

class GameMama {
    var $mPid = null;
    var $mAttrs=array();
    function GameMama($pid,$name_zh,$name_en) {
        $this->mDB = new DB(DSN_GAME);
        $this->mAttrs['name_zh'] = $name_zh;
        $this->mAttrs['name_en'] = $name_en;
        $this->mAttrs['pid'] = $pid;
    }
    function set($attr,$val) {
        if (isset($this->mAttrs[$attr])) {
            if (!is_array($this->mAttrs[$attr])) {
                $this->mAttrs[$attr] = array();
            }
            $this->mAttrs[$attr][] = $val;
        } else {
            $this->mAttrs[$attr]=$val;
        }
    }
    function produce() {
        $time = time();
        $sql = 'INSERT INTO game 
                (updated_time) 
                VALUES ('.$time.')';
        $this->mDB->initSql($sql);
        $this->mDB->query();
        if (!($gid=$this->mDB->getInsertId())) {
            return false;
        }
        $game = new Game($gid);
        $game->mAttrs = $this->mAttrs;
        return $game->save();
    }
}



class GWHook {
    static $callbacks;
    function add($key,$func) {
        @self::$callbacks[$key][] = $func;
        array_unique($callbacks[$key]);
    }
    function get($key) {
        if (isset($callbacks[$key])) {
            return self::$callbacks[$key];
        }
        return array();
    }
}
